package com.xr.maintain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xr.maintain.service.TargetFoodService;
import com.xr.maintain.util.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description : 
 *
 * @date : 2021/6/7
 *
 * @Copyright :
 *
 * @author : 谯
 */
@Service
@Slf4j
public class TargetFoodServiceImpl implements TargetFoodService {

    @Override
    public String selectAndInsert(Class sourceClass, Class targetClass, Class object) {

        Integer count = selectCount(sourceClass);
//        插入失败的数据的id集合
        List<String> errorList = new ArrayList<>();

        for (Integer i = 0; i < count; i++) {
            BaseMapper targetBaseMapper = (BaseMapper) SpringBeanUtils.getBean(targetClass);
            IPage iPage = selectPage(sourceClass,new Page(i+1,1000));
            List records = iPage.getRecords();
            for (Object record : records) {
                Object o = null;
                try {
                    o = object.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                BeanUtils.copyProperties(record, o);
                try {
                    targetBaseMapper.insert(o);
                } catch (Exception e) {
                    e.printStackTrace();
                    String s =record.toString();
                    errorList.add(record.toString());
                    System.out.println(s);
                }
            }
        }

        if (errorList.size()>0){
            return errorList.toString();
        }
        return null;
    }


    /**
     * @Description:
     * 分页查询
     *
     * @param tCass: 需要查询的表对应的表的mapper的class对象
     * @param page: 分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage
     */
    private IPage selectPage(Class tCass,Page<Object> page) {
        BaseMapper baseMapper = (BaseMapper) SpringBeanUtils.getBean(tCass);
        IPage selectPage = baseMapper.selectPage(page, new QueryWrapper());
        return selectPage;
    }

    /**
     * @Description:
     * 查询表中所有的数据总数
     *
     * @param tlass
     * @return java.lang.Integer
     */
    private Integer selectCount(Class tlass) {
        BaseMapper baseMapper = (BaseMapper) SpringBeanUtils.getBean(tlass);
        Integer count = baseMapper.selectCount(new QueryWrapper());
        return count;
    }

}
